package cn.tpshion.vm.handler.task;

import cn.tpshion.vm.common.constant.NodeType;
import cn.tpshion.vm.common.utils.AssertUtil;
import cn.tpshion.vm.common.utils.IdUtil;
import cn.tpshion.vm.domain.support.MavenData;
import cn.tpshion.vm.domain.support.NodeContext;
import cn.tpshion.vm.handler.task.support.AbstractNodeHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import java.io.File;

@Slf4j
@Component
public class MavenHandler extends AbstractNodeHandler<MavenData> {

    @Override
    public NodeType getNodeType() {
        return NodeType.MAVEN;
    }

    @Override
    protected void handleNode(NodeContext context) throws Exception{
        MavenData data = getData(context);
        AssertUtil.isBlank(data.getDockerImage(), "节点镜像不能为空");
        String workspace = StringUtils.isBlank(data.getWorkDir()) ?
                context.getWorkspace() : context.getWorkspace() + File.separator + data.getWorkDir();

        String pomPath = StringUtils.isBlank(data.getPomPath()) ?
                workspace : workspace + File.separator + data.getPomPath();

        String dockerPath = nodeConfig.getDockerPath() + File.separator + context.getTaskId();
        String dockerImage = data.getDockerImage();

        String command = String.format("docker run -i --name %s --rm -v %s:/home/repo -v %s:%s -w %s %s %s",
                context.getDockerId(), nodeConfig.getMavenRepo(), pomPath, dockerPath, dockerPath, dockerImage, data.getCommand());
        int exitCode = localCommandHandler.exec(command, workspace, context);
        AssertUtil.isTrue(exitCode != 0, "执行失败");
    }

    @Override
    protected void beforeHandler(NodeContext context) {
        super.beforeHandler(context);
        context.setDockerId(IdUtil.getDockerId());
    }

    @Override
    public void stop(NodeContext context) throws Exception {
        super.stop(context);
        if(StringUtils.isBlank(context.getDockerId())){
            return;
        }
        localCommandHandler.stop(context.getDockerId(), context);
    }
}
